<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>加密货币技术分析仪表板</title>
    
    <!-- 引入Chart.js用于图表展示 -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
    
    <!-- 引入Bootstrap用于样式 -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    
    <!-- 引入Font Awesome图标 -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    
    <!-- 引入自定义样式 -->
    <link rel="stylesheet" href="/static/style.css">
    
    <!-- 自定义样式 -->
    <style>
        /* 特定于dashboard.html的自定义样式 */
        .dashboard-header {
            padding: 2rem 0;
            margin-bottom: 2rem;
        }
        
        .indicator-card {
            text-align: center;
            padding: 1.5rem;
        }
        
        .indicator-value {
            font-size: 2rem;
            font-weight: bold;
            margin: 0.5rem 0;
        }
        
        .indicator-label {
            color: #6c757d;
            font-size: 0.9rem;
        }
        
        .loading {
            text-align: center;
            padding: 2rem;
        }
        
        .spinner-border {
            width: 3rem;
            height: 3rem;
        }
        
        .chart-container {
            position: relative;
            height: 400px;
            margin: 1rem 0;
        }
        
        .controls {
            background: white;
            padding: 1.5rem;
            border-radius: 15px;
            margin-bottom: 2rem;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            border-radius: 25px;
            padding: 0.5rem 2rem;
        }
        
        .btn-primary:hover {
            background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
        }
        
        .error-message {
            background-color: #f8d7da;
            color: #721c24;
            padding: 1rem;
            border-radius: 10px;
            margin: 1rem 0;
        }
        
        /* 市场数据样式 */
        .currency-btn {
            margin: 2px;
            padding: 2px 8px;
            font-size: 0.75rem;
            border-radius: 12px;
        }
        
        .currency-btn.active {
            background-color: #007bff;
            color: white;
            border-color: #007bff;
        }
        
        .market-data-error {
            background-color: #fff3cd;
            color: #856404;
            padding: 0.5rem;
            border-radius: 5px;
            margin: 0.5rem 0;
            font-size: 0.8rem;
        }
        
        .market-data-loading {
            opacity: 0.6;
            pointer-events: none;
        }
        
        .currency-display {
            transition: all 0.3s ease;
        }
        
        .currency-display.updating {
            opacity: 0.5;
            transform: scale(0.95);
        }
        
        .market-data-unavailable {
            background: linear-gradient(135deg, #ffeaa7 0%, #fab1a0 100%);
            color: #2d3436;
            padding: 1rem;
            border-radius: 10px;
            text-align: center;
            margin: 1rem 0;
        }
        
        .currency-conversion-loading {
            position: relative;
        }
        
        .currency-conversion-loading::after {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255, 255, 255, 0.8);
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 10px;
        }
    </style>
</head>
<body>
    <!-- 头部 -->
    <div class="dashboard-header gradient-bg">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <h1 class="mb-0 text-white fw-bold">🚀 加密货币技术分析仪表板</h1>
                    <p class="mb-0 mt-2 text-white-50">实时技术指标分析与交易信号</p>
                </div>
                <div class="col-md-4 text-end">
                    <div id="lastUpdate" class="small text-white-50">
                        最后更新: --
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="container">
        <!-- 控制面板 -->
        <div class="controls card card-hover">
            <div class="card-body p-4">
                <div class="row align-items-end">
                    <div class="col-md-3">
                        <label for="symbolSelect" class="form-label fw-bold">选择币种</label>
                        <div class="input-group">
                            <span class="input-group-text bg-transparent border-end-0">
                                <i class="fas fa-coins text-primary"></i>
                            </span>
                            <select id="symbolSelect" class="form-select border-start-0 ps-0">
                                <option value="BTC">Bitcoin (BTC)</option>
                                <option value="ETH">Ethereum (ETH)</option>
                                <option value="ADA">Cardano (ADA)</option>
                                <option value="DOT">Polkadot (DOT)</option>
                                <option value="LINK">Chainlink (LINK)</option>
                                <option value="LTC">Litecoin (LTC)</option>
                                <option value="XRP">Ripple (XRP)</option>
                                <option value="BNB">Binance Coin (BNB)</option>
                                <option value="SOL">Solana (SOL)</option>
                                <option value="MATIC">Polygon (MATIC)</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <label for="timeframeSelect" class="form-label fw-bold">时间框架</label>
                        <div class="input-group">
                            <span class="input-group-text bg-transparent border-end-0">
                                <i class="fas fa-clock text-primary"></i>
                            </span>
                            <select id="timeframeSelect" class="form-select border-start-0 ps-0">
                                <option value="1h">1小时</option>
                                <option value="4h">4小时</option>
                                <option value="1d">1天</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <label for="periodSelect" class="form-label fw-bold">历史周期</label>
                        <div class="input-group">
                            <span class="input-group-text bg-transparent border-end-0">
                                <i class="fas fa-calendar-alt text-primary"></i>
                            </span>
                            <select id="periodSelect" class="form-select border-start-0 ps-0">
                                <option value="7d">7天</option>
                                <option value="30d" selected>30天</option>
                                <option value="90d">90天</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <label for="currencySelect" class="form-label fw-bold">显示货币</label>
                        <div class="input-group">
                            <span class="input-group-text bg-transparent border-end-0">
                                <i class="fas fa-dollar-sign text-primary"></i>
                            </span>
                            <select id="currencySelect" class="form-select border-start-0 ps-0">
                                <option value="USD" selected>美元 (USD)</option>
                                <option value="EUR">欧元 (EUR)</option>
                                <option value="CNY">人民币 (CNY)</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <button id="analyzeBtn" class="btn btn-primary w-100">
                            <i class="fas fa-chart-bar me-2"></i>
                            <span id="analyzeText">开始分析</span>
                            <span id="analyzeSpinner" class="spinner-border spinner-border-sm d-none ms-2" role="status"></span>
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 错误消息 -->
        <div id="errorMessage" class="error-message d-none"></div>

        <!-- 市场数据卡片 -->
        <div id="marketDataSection" class="d-none">
            <div class="row mb-4">
                <div class="col-12">
                    <h5 class="mb-3">
                        <i class="fas fa-chart-pie me-2"></i>市场数据
                        <span id="marketDataLoading" class="spinner-border spinner-border-sm ms-2 d-none" role="status"></span>
                    </h5>
                </div>
                
                <!-- 市值 -->
                <div class="col-md-3">
                    <div class="card">
                        <div class="card-body indicator-card">
                            <div class="indicator-label">
                                <i class="fas fa-coins me-1"></i>市值
                            </div>
                            <div id="marketCapValue" class="indicator-value">--</div>
                            <div id="marketCapRank" class="small text-muted">排名: --</div>
                        </div>
                    </div>
                </div>
                
                <!-- 24小时交易量 -->
                <div class="col-md-3">
                    <div class="card">
                        <div class="card-body indicator-card">
                            <div class="indicator-label">
                                <i class="fas fa-chart-bar me-1"></i>24h交易量
                            </div>
                            <div id="volumeValue" class="indicator-value">--</div>
                            <div id="volumeChange" class="small">变化: --</div>
                        </div>
                    </div>
                </div>
                
                <!-- 货币转换 -->
                <div class="col-md-3">
                    <div class="card">
                        <div class="card-body indicator-card">
                            <div class="indicator-label">
                                <i class="fas fa-exchange-alt me-1"></i>汇率信息
                            </div>
                            <div id="exchangeRateValue" class="indicator-value">--</div>
                            <div id="exchangeRateTime" class="small text-muted">更新: --</div>
                        </div>
                    </div>
                </div>
                
                <!-- 多货币显示 -->
                <div class="col-md-3">
                    <div class="card">
                        <div class="card-body indicator-card">
                            <div class="indicator-label">
                                <i class="fas fa-globe me-1"></i>多货币价格
                            </div>
                            <div id="multiCurrencyValue" class="indicator-value">--</div>
                            <div id="currencySelector" class="small">
                                <button class="btn btn-sm btn-outline-primary currency-btn active" data-currency="USD">USD</button>
                                <button class="btn btn-sm btn-outline-primary currency-btn" data-currency="EUR">EUR</button>
                                <button class="btn btn-sm btn-outline-primary currency-btn" data-currency="CNY">CNY</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 主要指标卡片 -->
        <div id="indicatorsSection" class="d-none">
            <div class="row">
                <div class="col-12">
                    <h5 class="mb-3">
                        <i class="fas fa-chart-line me-2"></i>技术指标
                    </h5>
                </div>
                
                <!-- RSI -->
                <div class="col-md-3">
                    <div class="card">
                        <div class="card-body indicator-card">
                            <div class="indicator-label">RSI (14)</div>
                            <div id="rsiValue" class="indicator-value">--</div>
                            <div id="rsiSignal" class="signal-badge signal-neutral">中性</div>
                        </div>
                    </div>
                </div>
                
                <!-- MACD -->
                <div class="col-md-3">
                    <div class="card">
                        <div class="card-body indicator-card">
                            <div class="indicator-label">MACD</div>
                            <div id="macdValue" class="indicator-value">--</div>
                            <div id="macdSignal" class="signal-badge signal-neutral">中性</div>
                        </div>
                    </div>
                </div>
                
                <!-- 布林带 -->
                <div class="col-md-3">
                    <div class="card">
                        <div class="card-body indicator-card">
                            <div class="indicator-label">布林带位置</div>
                            <div id="bbValue" class="indicator-value">--</div>
                            <div id="bbSignal" class="signal-badge signal-neutral">中性</div>
                        </div>
                    </div>
                </div>
                
                <!-- 移动平均线 -->
                <div class="col-md-3">
                    <div class="card">
                        <div class="card-body indicator-card">
                            <div class="indicator-label">MA趋势</div>
                            <div id="maValue" class="indicator-value">--</div>
                            <div id="maSignal" class="signal-badge signal-neutral">中性</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 详细指标表格 -->
        <div id="detailsSection" class="d-none">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">📈 详细技术指标</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>指标</th>
                                        <th>数值</th>
                                        <th>信号</th>
                                    </tr>
                                </thead>
                                <tbody id="indicatorsTable">
                                </tbody>
                            </table>
                        </div>
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-header">
                                    <h6 class="mb-0">🎯 综合交易信号</h6>
                                </div>
                                <div class="card-body">
                                    <div id="overallSignal" class="text-center">
                                        <div class="indicator-value">分析中...</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 图表区域 -->
        <div id="chartSection" class="d-none">
            <div class="card card-hover">
                <div class="card-header d-flex align-items-center">
                    <i class="fas fa-chart-line me-2"></i>
                    <h5 class="mb-0">价格走势与技术指标</h5>
                </div>
                <div class="card-body p-3">
                    <div class="chart-container">
                        <canvas id="priceChart"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <!-- 性能信息 -->
        <div id="performanceSection" class="d-none">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">⚡ 性能信息</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-3">
                            <strong>数据点数:</strong>
                            <span id="dataPoints">--</span>
                        </div>
                        <div class="col-md-3">
                            <strong>计算耗时:</strong>
                            <span id="calculationTime">--</span>
                        </div>
                        <div class="col-md-3">
                            <strong>分析时间:</strong>
                            <span id="analysisTime">--</span>
                        </div>
                        <div class="col-md-3">
                            <strong>状态:</strong>
                            <span id="analysisStatus" class="badge bg-success">就绪</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let currentChart = null;
        let currentData = null;
        let currentMarketData = null;
        let currentCurrencyInfo = null;
        let selectedCurrency = 'USD';

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 绑定事件
            document.getElementById('analyzeBtn').addEventListener('click', performAnalysis);
            document.getElementById('currencySelect').addEventListener('change', onCurrencyChange);
            
            // 绑定货币按钮事件
            document.querySelectorAll('.currency-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const currency = this.dataset.currency;
                    switchCurrency(currency);
                });
            });
            
            // 自动执行一次分析
            performAnalysis();
        });

        // 执行技术分析
        async function performAnalysis() {
            const symbol = document.getElementById('symbolSelect').value;
            const timeframe = document.getElementById('timeframeSelect').value;
            const period = document.getElementById('periodSelect').value;
            const currencies = ['USD', 'EUR', 'CNY'];

            // 显示加载状态
            showLoading(true);
            showMarketDataLoading(true);
            hideError();

            try {
                // 调用API
                const response = await fetch('/api/v1/technical-analysis', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        symbol: symbol,
                        timeframe: timeframe,
                        period: period,
                        currencies: currencies
                    })
                });

                const data = await response.json();

                if (data.success) {
                    // 保存数据
                    currentData = data;
                    currentMarketData = data.market_data;
                    currentCurrencyInfo = data.currency_info;
                    
                    // 显示结果
                    displayResults(data);
                    displayMarketData(data.market_data, data.currency_info, data.error);
                    
                    // 获取历史数据用于图表
                    await loadHistoricalData(symbol, timeframe, period);
                } else {
                    showError(data.error || '分析失败');
                }

            } catch (error) {
                console.error('分析错误:', error);
                showError('网络错误或服务器异常');
            } finally {
                showLoading(false);
                showMarketDataLoading(false);
            }
        }

        // 显示分析结果
        function displayResults(data) {
            // 更新主要指标卡片
            updateIndicatorCards(data.indicators, data.signals);
            
            // 更新详细表格
            updateDetailsTable(data.indicators, data.signals);
            
            // 更新性能信息
            updatePerformanceInfo(data);
            
            // 显示各个区域
            document.getElementById('marketDataSection').classList.remove('d-none');
            document.getElementById('indicatorsSection').classList.remove('d-none');
            document.getElementById('detailsSection').classList.remove('d-none');
            document.getElementById('performanceSection').classList.remove('d-none');
            
            // 更新最后更新时间
            document.getElementById('lastUpdate').textContent = 
                `最后更新: ${new Date().toLocaleString()}`;
        }

        // 更新指标卡片
        function updateIndicatorCards(indicators, signals) {
            // RSI
            if (indicators.rsi !== undefined) {
                document.getElementById('rsiValue').textContent = indicators.rsi.toFixed(2);
                updateSignalBadge('rsiSignal', signals.rsi);
            }

            // MACD
            if (indicators.macd) {
                const macdValue = indicators.macd.histogram.toFixed(2);
                document.getElementById('macdValue').textContent = macdValue;
                updateSignalBadge('macdSignal', signals.macd);
            }

            // 布林带 (这里简化显示中轨值)
            if (indicators.bollinger_bands) {
                const bbValue = indicators.bollinger_bands.middle.toFixed(2);
                document.getElementById('bbValue').textContent = bbValue;
                updateSignalBadge('bbSignal', signals.bollinger || 'neutral');
            }

            // 移动平均线
            if (indicators.sma_20 && indicators.sma_50) {
                const trend = indicators.sma_20 > indicators.sma_50 ? '上升' : '下降';
                document.getElementById('maValue').textContent = trend;
                const signal = indicators.sma_20 > indicators.sma_50 ? 'bullish' : 'bearish';
                updateSignalBadge('maSignal', signal);
            }
        }

        // 更新信号徽章
        function updateSignalBadge(elementId, signal) {
            const element = document.getElementById(elementId);
            element.className = 'signal-badge';
            
            switch(signal) {
                case 'bullish':
                    element.classList.add('signal-bullish');
                    element.textContent = '看涨';
                    break;
                case 'bearish':
                    element.classList.add('signal-bearish');
                    element.textContent = '看跌';
                    break;
                case 'overbought':
                    element.classList.add('signal-overbought');
                    element.textContent = '超买';
                    break;
                case 'oversold':
                    element.classList.add('signal-oversold');
                    element.textContent = '超卖';
                    break;
                default:
                    element.classList.add('signal-neutral');
                    element.textContent = '中性';
            }
        }

        // 更新详细表格
        function updateDetailsTable(indicators, signals) {
            const tbody = document.getElementById('indicatorsTable');
            tbody.innerHTML = '';

            const indicatorList = [
                { key: 'rsi', name: 'RSI (14)', format: (v) => v.toFixed(2) },
                { key: 'macd', name: 'MACD', format: (v) => v.macd.toFixed(2) },
                { key: 'sma_20', name: 'SMA (20)', format: (v) => v.toFixed(2) },
                { key: 'ema_12', name: 'EMA (12)', format: (v) => v.toFixed(2) }
            ];

            indicatorList.forEach(indicator => {
                if (indicators[indicator.key] !== undefined) {
                    const row = tbody.insertRow();
                    row.innerHTML = `
                        <td>${indicator.name}</td>
                        <td>${indicator.format(indicators[indicator.key])}</td>
                        <td><span class="signal-badge signal-neutral">${getSignalText(signals[indicator.key] || 'neutral')}</span></td>
                    `;
                }
            });

            // 更新综合信号
            updateOverallSignal(signals);
        }

        // 更新综合信号
        function updateOverallSignal(signals) {
            const signalValues = Object.values(signals);
            const bullishCount = signalValues.filter(s => s === 'bullish').length;
            const bearishCount = signalValues.filter(s => s === 'bearish').length;
            
            let overallSignal = 'neutral';
            let signalText = '中性';
            
            if (bullishCount > bearishCount) {
                overallSignal = 'bullish';
                signalText = '看涨';
            } else if (bearishCount > bullishCount) {
                overallSignal = 'bearish';
                signalText = '看跌';
            }

            const element = document.getElementById('overallSignal');
            element.innerHTML = `
                <div class="indicator-value">${signalText}</div>
                <div class="small text-muted">
                    看涨信号: ${bullishCount} | 看跌信号: ${bearishCount}
                </div>
            `;
        }

        // 获取信号文本
        function getSignalText(signal) {
            const signalMap = {
                'bullish': '看涨',
                'bearish': '看跌',
                'overbought': '超买',
                'oversold': '超卖',
                'neutral': '中性'
            };
            return signalMap[signal] || '中性';
        }

        // 更新性能信息
        function updatePerformanceInfo(data) {
            document.getElementById('dataPoints').textContent = data.data_points_used;
            document.getElementById('calculationTime').textContent = `${data.calculation_time_ms.toFixed(2)}ms`;
            document.getElementById('analysisTime').textContent = new Date(data.timestamp).toLocaleString();
            document.getElementById('analysisStatus').textContent = '完成';
        }

        // 加载历史数据并绘制图表
        async function loadHistoricalData(symbol, timeframe, period) {
            try {
                const response = await fetch(`/api/v1/historical-data?symbol=${symbol}&timeframe=${timeframe}&period=${period}`);
                const data = await response.json();

                if (data.success && data.data.length > 0) {
                    drawChart(data.data, symbol);
                    document.getElementById('chartSection').classList.remove('d-none');
                }
            } catch (error) {
                console.error('加载历史数据失败:', error);
            }
        }

        // 绘制价格图表
        function drawChart(data, symbol) {
            const ctx = document.getElementById('priceChart').getContext('2d');
            
            // 销毁现有图表
            if (currentChart) {
                currentChart.destroy();
            }

            // 准备数据
            const labels = data.map(d => new Date(d.timestamp * 1000));
            const prices = data.map(d => d.close);

            currentChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: [{
                        label: `${symbol} 价格`,
                        data: prices,
                        borderColor: 'rgb(75, 192, 192)',
                        backgroundColor: 'rgba(75, 192, 192, 0.1)',
                        tension: 0.1,
                        fill: true
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        x: {
                            type: 'time',
                            time: {
                                displayFormats: {
                                    hour: 'MM-dd HH:mm',
                                    day: 'MM-dd'
                                }
                            }
                        },
                        y: {
                            beginAtZero: false
                        }
                    },
                    plugins: {
                        legend: {
                            display: true,
                            position: 'top'
                        },
                        tooltip: {
                            mode: 'index',
                            intersect: false
                        }
                    }
                }
            });
        }

        // 显示/隐藏加载状态
        function showLoading(show) {
            const btn = document.getElementById('analyzeBtn');
            const text = document.getElementById('analyzeText');
            const spinner = document.getElementById('analyzeSpinner');

            if (show) {
                btn.disabled = true;
                text.textContent = '分析中...';
                spinner.classList.remove('d-none');
            } else {
                btn.disabled = false;
                text.textContent = '📊 开始分析';
                spinner.classList.add('d-none');
            }
        }

        // 显示错误信息
        function showError(message) {
            const errorDiv = document.getElementById('errorMessage');
            errorDiv.textContent = `❌ ${message}`;
            errorDiv.classList.remove('d-none');
        }

        // 隐藏错误信息
        function hideError() {
            document.getElementById('errorMessage').classList.add('d-none');
        }

        // 显示市场数据，支持优雅降级
        function displayMarketData(marketData, currencyInfo, errorMessage) {
            const marketDataSection = document.getElementById('marketDataSection');
            
            // 如果有错误消息，显示警告
            if (errorMessage) {
                showMarketDataWarning(errorMessage);
            } else {
                hideMarketDataError();
            }
            
            // 如果完全没有市场数据，显示错误并隐藏区域
            if (!marketData) {
                showMarketDataError('市场数据暂时不可用，请稍后重试');
                marketDataSection.classList.add('d-none');
                return;
            }

            // 显示市场数据区域
            marketDataSection.classList.remove('d-none');

            try {
                // 更新市值（支持fallback）
                if (marketData.market_cap && marketData.market_cap[selectedCurrency]) {
                    const marketCap = marketData.market_cap[selectedCurrency];
                    document.getElementById('marketCapValue').textContent = formatCurrency(marketCap, selectedCurrency);
                } else if (marketData.market_cap && marketData.market_cap.USD) {
                    // Fallback到USD
                    const marketCapUSD = marketData.market_cap.USD;
                    document.getElementById('marketCapValue').textContent = formatCurrency(marketCapUSD, 'USD') + ' (USD)';
                } else {
                    document.getElementById('marketCapValue').textContent = '暂无数据';
                }

                // 更新市值排名
                if (marketData.market_cap_rank) {
                    document.getElementById('marketCapRank').textContent = `排名: #${marketData.market_cap_rank}`;
                } else {
                    document.getElementById('marketCapRank').textContent = '排名: --';
                }

                // 更新交易量（支持fallback）
                if (marketData.volume_24h && marketData.volume_24h[selectedCurrency]) {
                    const volume = marketData.volume_24h[selectedCurrency];
                    document.getElementById('volumeValue').textContent = formatCurrency(volume, selectedCurrency);
                } else if (marketData.volume_24h && marketData.volume_24h.USD) {
                    // Fallback到USD
                    const volumeUSD = marketData.volume_24h.USD;
                    document.getElementById('volumeValue').textContent = formatCurrency(volumeUSD, 'USD') + ' (USD)';
                } else {
                    document.getElementById('volumeValue').textContent = '暂无数据';
                }

                // 更新交易量变化
                if (marketData.volume_change_24h !== undefined && marketData.volume_change_24h !== null) {
                    const change = marketData.volume_change_24h;
                    const changeElement = document.getElementById('volumeChange');
                    changeElement.textContent = `变化: ${change >= 0 ? '+' : ''}${change.toFixed(2)}%`;
                    changeElement.className = `small ${change >= 0 ? 'text-success' : 'text-danger'}`;
                } else {
                    document.getElementById('volumeChange').textContent = '变化: --';
                }

                // 更新汇率信息（支持fallback）
                if (currencyInfo && currencyInfo.rates && currencyInfo.rates[selectedCurrency]) {
                    const rate = currencyInfo.rates[selectedCurrency];
                    if (selectedCurrency !== 'USD') {
                        document.getElementById('exchangeRateValue').textContent = `1 USD = ${rate.toFixed(4)} ${selectedCurrency}`;
                    } else {
                        document.getElementById('exchangeRateValue').textContent = '基准货币';
                    }
                    
                    if (currencyInfo.last_updated) {
                        const updateTime = new Date(currencyInfo.last_updated).toLocaleTimeString();
                        document.getElementById('exchangeRateTime').textContent = `更新: ${updateTime}`;
                    }
                } else {
                    // Fallback汇率显示
                    const fallbackRates = { USD: 1.0, EUR: 0.85, CNY: 7.2 };
                    const fallbackRate = fallbackRates[selectedCurrency] || 1.0;
                    document.getElementById('exchangeRateValue').textContent = selectedCurrency !== 'USD' ? 
                        `1 USD ≈ ${fallbackRate.toFixed(4)} ${selectedCurrency} (估算)` : '基准货币';
                    document.getElementById('exchangeRateTime').textContent = '更新: 使用估算汇率';
                }

                // 更新多货币显示
                updateMultiCurrencyDisplay(marketData, currencyInfo);

            } catch (error) {
                console.error('显示市场数据错误:', error);
                showMarketDataError('市场数据显示异常，请刷新页面重试');
            }
        }

        // 更新多货币显示
        function updateMultiCurrencyDisplay(marketData, currencyInfo) {
            if (!marketData || !marketData.market_cap) return;

            const currencies = ['USD', 'EUR', 'CNY'];
            let displayText = '';

            currencies.forEach(currency => {
                const value = marketData.market_cap[currency];
                if (value) {
                    const formatted = formatCurrency(value, currency, true);
                    displayText += `${currency}: ${formatted}\n`;
                }
            });

            document.getElementById('multiCurrencyValue').textContent = 
                marketData.market_cap[selectedCurrency] ? 
                formatCurrency(marketData.market_cap[selectedCurrency], selectedCurrency) : '--';
        }

        // 货币切换
        function switchCurrency(currency) {
            if (selectedCurrency === currency) return;

            selectedCurrency = currency;
            
            // 更新按钮状态
            document.querySelectorAll('.currency-btn').forEach(btn => {
                btn.classList.toggle('active', btn.dataset.currency === currency);
            });

            // 更新下拉选择器
            document.getElementById('currencySelect').value = currency;

            // 重新显示市场数据
            if (currentMarketData) {
                displayMarketData(currentMarketData, currentCurrencyInfo);
            }
        }

        // 货币选择器变化事件
        function onCurrencyChange() {
            const currency = document.getElementById('currencySelect').value;
            switchCurrency(currency);
        }

        // 格式化货币显示
        function formatCurrency(value, currency, compact = false) {
            if (!value || isNaN(value)) return '--';

            const symbols = {
                'USD': '$',
                'EUR': '€',
                'CNY': '¥'
            };

            const symbol = symbols[currency] || currency;

            if (compact && value >= 1000000000) {
                return `${symbol}${(value / 1000000000).toFixed(2)}B`;
            } else if (compact && value >= 1000000) {
                return `${symbol}${(value / 1000000).toFixed(2)}M`;
            } else if (compact && value >= 1000) {
                return `${symbol}${(value / 1000).toFixed(2)}K`;
            } else {
                return `${symbol}${value.toLocaleString(undefined, {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                })}`;
            }
        }

        // 显示市场数据加载状态
        function showMarketDataLoading(show) {
            const spinner = document.getElementById('marketDataLoading');
            if (show) {
                spinner.classList.remove('d-none');
                document.getElementById('marketDataSection').classList.add('market-data-loading');
            } else {
                spinner.classList.add('d-none');
                document.getElementById('marketDataSection').classList.remove('market-data-loading');
            }
        }

        // 显示市场数据错误
        function showMarketDataError(message) {
            // 在市场数据区域显示错误信息
            const marketCapValue = document.getElementById('marketCapValue');
            const volumeValue = document.getElementById('volumeValue');
            const exchangeRateValue = document.getElementById('exchangeRateValue');
            const multiCurrencyValue = document.getElementById('multiCurrencyValue');

            marketCapValue.innerHTML = `<small class="market-data-error">${message}</small>`;
            volumeValue.innerHTML = `<small class="market-data-error">数据不可用</small>`;
            exchangeRateValue.innerHTML = `<small class="market-data-error">汇率不可用</small>`;
            multiCurrencyValue.innerHTML = `<small class="market-data-error">--</small>`;
        }
        
        // 显示市场数据警告（部分数据可用）
        function showMarketDataWarning(message) {
            // 在市场数据区域顶部显示警告横幅
            let warningBanner = document.getElementById('marketDataWarning');
            if (!warningBanner) {
                warningBanner = document.createElement('div');
                warningBanner.id = 'marketDataWarning';
                warningBanner.className = 'alert alert-warning alert-dismissible fade show mb-3';
                warningBanner.innerHTML = `
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    <span id="warningMessage"></span>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                `;
                
                const marketDataSection = document.getElementById('marketDataSection');
                marketDataSection.insertBefore(warningBanner, marketDataSection.firstChild);
            }
            
            document.getElementById('warningMessage').textContent = message;
            warningBanner.style.display = 'block';
        }
        
        // 隐藏市场数据错误信息
        function hideMarketDataError() {
            const warningBanner = document.getElementById('marketDataWarning');
            if (warningBanner) {
                warningBanner.style.display = 'none';
            }
        }
        
        // 显示市场数据加载状态
        function showMarketDataLoading(show) {
            const loadingSpinner = document.getElementById('marketDataLoading');
            const marketDataSection = document.getElementById('marketDataSection');
            
            if (show) {
                loadingSpinner.classList.remove('d-none');
                marketDataSection.classList.add('market-data-loading');
            } else {
                loadingSpinner.classList.add('d-none');
                marketDataSection.classList.remove('market-data-loading');
            }
        }
    </script>
    
    <footer class="text-center mt-4 mb-3">
        <div class="container">
            <div class="py-3 px-4 bg-dark bg-opacity-50 rounded-pill d-inline-block shadow">
                <a href="https://github.com/Aci1998/crypto-price-checker" target="_blank" class="text-white text-decoration-none fs-5">
                    <i class="fab fa-github me-2"></i> <strong>GitHub 开源项目</strong>
                </a>
            </div>
        </div>
    </footer>
</body>
</html>